package com.fanyouzhao.ssm251.controller;

import com.fanyouzhao.ssm251.annotation.NeedsLogin;
import com.fanyouzhao.ssm251.pojo.User;
import com.fanyouzhao.ssm251.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @Author: fanyouzhao
 * @Date: 11:27 2021/5/25
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService = null;

    // 在接口中代入参数
/*    @PostMapping("/reg")
    public void register(@RequestParam(value = "phone",required = false,defaultValue = "152mm") String phone,@RequestParam("pwd") String pwd){
        System.out.println("phone = " + phone);
        System.out.println("pwd = " + pwd);
    }*/

    // 在接口中代入参数，对象
    //@RequestBody传递多个参数注入
    /*@PostMapping("/reg")
    public void register(@RequestBody User user){
        System.out.println("user = " + user);
    }*/

    // 向前端返回一个Json对象，注意是对象，是可以直接key-value的。而不是jsp页面的跳转
    @PostMapping("/reg")
    @ResponseBody
    public User register(@RequestBody User user){
        user.setId(1001);
        return user;
    }

    @PostMapping("/index")
    public void index(@RequestHeader("auth") String auth){
        System.out.println("auth = " + auth);
    }

    // @RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET})
/*    @PostMapping("login")
    public String login(){
        System.out.println("执行了/user/login");
        return "login";
    }*/

    /*@PostMapping("login")
    @ResponseBody
    public User login(@RequestParam(value = "id") Integer id){
        System.out.println("执行了/user/login");
        User user = userService.login(id);
        return user;
    }*/

    /**
     * @param  modelAndView 表示用Spring的方式创建一个bean，在mvc中，声明的参数往往都能自动注入（DI）
     * */
    @RequestMapping("/loginInModel")
    public ModelAndView loginInModel(ModelAndView modelAndView){
        // 指定数据Model
        User user = new User();
        user.setName("张无忌");
        modelAndView.addObject("user",user);
        // 指定视图名称,并转发，至WEB-INF/jsp/login.jsp
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @PostMapping("/loginWithSession")
    public String loginWithSession(HttpSession httpSession){
        httpSession.setAttribute("phone","18096222213");
        return "loginWithSession";
    }

}
